#include "utils.h"



QString FileUtils::getSavePath(QString filter, QWidget* parent) {
	return QFileDialog::getExistingDirectory(parent, QString("保存"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
	//return QFileDialog::getSaveFileName(parent, QString("保存"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), filter);
}

void FileUtils::createDir(const QString& dirName) {
	//创建缓存文件夹
	QDir dir;
	if (!dirName.isEmpty() && !dir.exists(dirName)) {
		dir.mkpath(dirName);
	}
}

void FileUtils::deleteFile(const QString& path) {
	if (path.isEmpty()) {
		return;
	}
	try {
		QFileInfo file(path);
		if (file.isFile()) {
			//若是文件，直接删除
			file.dir().remove(file.fileName());
		} else if (file.isDir()) {
			//若是文件夹，先删除文件夹下所有的文件，再删除文件夹
			QDir dir(path);
			dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
			QFileInfoList fileList = dir.entryInfoList();
			foreach(QFileInfo fileInfo, fileList) {
				deleteFile(fileInfo.absoluteFilePath());
			}
			//删除当前文件夹
			dir.removeRecursively();
		}
	} catch (const std::exception& e) {
		qCritical() << e.what();
		throw MyError(MyErrorType::FILE_DELETE_ERROR);
	}
}

void FileUtils::deleteFiles(const QString& baseDir) {
	QDir dir;
	dir.setPath(baseDir);
	if (dir.exists()) {
		//获取文件夹下的所有文件
		dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
		dir.setSorting(QDir::Name);
		QFileInfoList fileList = dir.entryInfoList();
		try {
			//删除文件
			for (int i = 0; i < fileList.size(); i++) {
				deleteFile(fileList[i].absoluteFilePath());
			}
		} catch (const std::exception& e) {
			qCritical() << e.what();
			throw MyError(MyErrorType::FILE_DELETE_ERROR);
		}
	}
}

void FileUtils::deleteExpiresFiles(const QString& imgSavePath, const QDateTime& beforeTime) {
	if (imgSavePath.isEmpty()) {
		return;
	}
	try {
		//创建文件对象，并查询所有的文件
		QFileInfo file(imgSavePath);
		if (file.isDir()) {
			QDir dir(imgSavePath);
			dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
			QFileInfoList fileList = dir.entryInfoList();
			//遍历文件，若文件的创建日期小于beforeTime，则删除该文件
			foreach(QFileInfo fileInfo, fileList) {
				if (fileInfo.birthTime() < beforeTime) {
					deleteFile(fileInfo.absoluteFilePath());
				}
			}
		}
	} catch (const std::exception& e) {
		qCritical() << e.what();
		throw MyError(MyErrorType::FILE_DELETE_ERROR);
	}
}

QString FileUtils::getDesktopPath() {
	return QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
}